import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild ,ElementRef} from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { NzTableComponent } from 'ng-zorro-antd/table';
//导入公共依赖模块
import { ShareModule,NzMessageService } from '@app/share/share.module';
import { Router ,Route,ActivatedRoute} from '@angular/router';
// import { StoreService } from '@app/serves/app.serve';
import {getAllFiles_API,putFileOrFolderToRecycle_API} from '@/api/files';
import { getStore ,setStore,createShareUrl,copyToClipboard} from '@/utils';
import {DialogComponent} from './components/dialog.component'
export interface VirtualDataInterface {
  index: number;
  name: string;
  age: number;
  address: string;
}

@Component({
  selector: 'app-workSpace',
  templateUrl: './workSpace.component.html',
  standalone: true,
  imports: [ShareModule,DialogComponent],
  styleUrls: ['./workSpace.component.less']
})
export class WorkSpaceComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('dialogRef') dialogRef: DialogComponent;
  @ViewChild('virtualTable', { static: false }) nzTableComponent?: NzTableComponent<VirtualDataInterface>;
  private destroy$ = new Subject<boolean>();
  listOfData: VirtualDataInterface[] = [];
  dialogShow:boolean=false;
  queryParams:any={};
  pagelistbread: any[] = getStore({ name: 'pagelistbread'})||[]
  userInfo:any={}
  constructor(private message:NzMessageService,private router:Router,private route:ActivatedRoute) {
    this.userInfo= getStore({ name: 'userInfo' })
    //监听路由变化函数
    this.watchQueryChange()
  }

  trackByIndex(_: number, data: VirtualDataInterface): number {
    return data.index;
  }

  ngOnInit(): void {
    this.route.queryParams.subscribe((params) => {
      this.queryParams  = params
    });
  }

  _share(row){
     // 获取当前文件的信息  username, fileid, filename
     let url = createShareUrl(
      this.userInfo.username,
      row.id,
      row.name + "." + row.ext
    );
    return this.message.create('success',copyToClipboard(url));
  }

  _remove(row){
    let data={
      id: row.id,
      userid: this.userInfo.userid,
      type: row.type
    }
    let queryParams
    this.route.queryParams.subscribe((params) => {
     queryParams  = params
    });
    putFileOrFolderToRecycle_API(data).then(res=>{
      const {code,data,msg}=res
      if(code!==200)  this.message.create('error',msg)
        this.getList(queryParams.folderid)
        this.message.create('success',msg)
    }).catch(err=>{
      this.message.create('error',err)
    })
  }

  //返回文件夹上一级
  back(){
  const breadList=  getStore({ name: 'pagelistbread'})
  const lastBread=breadList.pop()
  this.pagelistbread=breadList
  setStore({ name: 'pagelistbread', content: breadList })
  if(lastBread.preFolderId){
    this.router.navigate(['/work/workSpace'],{
      queryParams: {
        folderid: lastBread.preFolderId,
      },
    })
  }else{
    this.router.navigate(['/work/workSpace'])
  }
  }


  // 手动实现watch监听
  watchQueryChange() {
    Object.defineProperty(this, 'queryParams', {
      get: ()=> {
      },
      set: (newV)=> {
        this.userInfo.userid&& this.getList(newV.folderid)
      }
    });
  }
   getParams = (url: string):any => {
    // var url = window.location.search; //获取url中"?"符后的字串
    let theParams = new Object();
    // 判断是否有问号
    if (url.indexOf("?") != -1) {
      // 把问号去掉
      let str = url.substr(1);
      // 判断是否有多个参数
      if(str.indexOf("&") != -1) {
        // 以&符分项组成数组
        let strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
          // 循环数组
          // theParams[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
          // 每一项等号左边为属性，等号右边为属性的值，值需要使用 decodeURI() 函数对通过 escape() 或 url 编码过的字符串进行解码。
          theParams[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
        }
      } else {
        // 只有一个参数
        let arr = str.split("=");
        theParams[arr[0]] = arr[1];
      }
    };
    return theParams;
  };


  pagelistbreadHandle = (item) => {
    // 修改文件夹面包屑
    this.pagelistbread.push({
      name: item.name,
      preFolderId:this.getParams(window.location.search).folderid||'',
    });
    setStore({ name: 'pagelistbread',content:this.pagelistbread })
  };

  _create(type:string){
    if(type === 'folder'){
      this.dialogRef._show('新增文件夹',{});
    }else if(type === 'excel'){
     //todo
     this.dialogRef._show('新增Excel',{});
    }
  }

  //处理文件夹或者文件的点击
  handleClick(item){
    const { type } = item;
    const eventMap = {
      folder: () => {
        // 处理面包屑
        this.pagelistbreadHandle(item);
        this.router.navigate(['/work/workSpace'],{
          queryParams: {
            folderid: item.id,
          },
        });
      },
      excel: () => this.router.navigate([`/work/workSpace/excel`],{
        queryParams: {
          id: item.id,
        },
      }),
    };
    eventMap[type] && eventMap[type]();
  }

  getList(folderid?:string){
    const queryP={
      userid:this.userInfo.userid
    }
    if(folderid)queryP['folderid']=folderid
    
    getAllFiles_API(queryP).then(res=>{
      const {code,data,msg}=res
      if(code!==200){
        this.message.create('error',msg)
      }else{
        this.listOfData=data.map((item,index)=>{
          return {
            ...item,
            index:index,
            type:item.type||'folder',
          }
        })
      }
    }).catch(err=>{
      this.message.create('error',err)
    })
  }

  ngAfterViewInit(): void {
    this.nzTableComponent?.cdkVirtualScrollViewport?.scrolledIndexChange
      .pipe(takeUntil(this.destroy$))
      .subscribe((data: number) => {
        console.log('scroll index to', data);
      });
   
  }

  ngOnDestroy(): void {
    this.destroy$.next(true);
    this.destroy$.complete();
    this.pagelistbread=[]
    setStore({ name: 'pagelistbread', content: [] })
  }
}
